package com.cherry.androidviewdemo.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.cherry.androidviewdemo.R
import com.cherry.androidviewdemo.utils.sp2px

/**
 * 如果继承的是ViewGroup，某些控件会绕过draw()，直接执行dispatchDraw()，所以onDraw()方法将不会被执行
 *
 * 可以将绘制 dispatchDraw()中执行
 * 或者设置背景
 * 或者调用setWillNotDraw(false)
 *
 * @author DongMS
 * @since 2020/5/28
 */
class CustomTextView : View {

    var text: String? = ""
    var textSize: Int = 0
    var textColor = Color.BLACK
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val rect = Rect()

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {

        val array = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView)
        text = array.getString(R.styleable.CustomTextView_text)
        textSize = array.getDimensionPixelSize(R.styleable.CustomTextView_textSize, 15f.sp2px(context).toInt())
        textColor = array.getColor(R.styleable.CustomTextView_textColor, Color.BLACK)

        array.recycle()

        paint.color = textColor
        paint.textSize = textSize.toFloat()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        if (text.isNullOrEmpty()) {
            return
        }

        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        var widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)

        if (widthMode == MeasureSpec.AT_MOST) {
            //根据文字测量宽度
            paint.getTextBounds(text!!, 0, text!!.length, rect)
            widthSize = rect.width() + paddingLeft + paddingRight
        }

        if (heightMode == MeasureSpec.AT_MOST) {
            //根据文字测量高度
            paint.getTextBounds(text!!, 0, text!!.length, rect)
            heightSize = rect.height() + paddingTop + paddingBottom
        }
        setMeasuredDimension(widthSize, heightSize)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val fontMetrics = paint.fontMetrics

        Log.d("---", "bottom=${fontMetrics.bottom}----top=${fontMetrics.top}")
        //top 负值 bottom 正值
        val dy = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom
        val baseLine = height / 2f + dy
        canvas.drawText(text!!, paddingLeft + 0f, baseLine, paint)
    }


}